package com.nash.demands;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.BaseColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class AgentsActivity extends Activity {
  private EditText ed;
  private ListView list;
  private DemandsActivity app;
  //private long currItemOnContextMenu;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.agents);

    app = (DemandsActivity) getParent();
    app.agentsActivity = this;
    list = (ListView) findViewById(R.id.listViewAgents);
    setAdapterAgents();

    ed = (EditText) findViewById(R.id.editTextSearch);
    ed.addTextChangedListener(new TextWatcher() {
      @Override
      public void afterTextChanged(Editable s) {
      }

      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        final SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter) list.getAdapter();
        filterAdapter.setFilterQueryProvider(filterQueryProvider);
        filterAdapter.setStringConversionColumn(1);
        filterAdapter.notifyDataSetChanged();
        filterAdapter.getFilter().filter(s.toString());
      }
    });

    // Делаем контекстное меню
    list.setFocusableInTouchMode(true);
/*    list.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View arg0, boolean arg1) {
        // Log.i("SampleApp", "onFocusChanged() - view=" + arg0);
      }
    });
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        //int selectedPosition = adapterView.getSelectedItemPosition();
        // Log.i("SampleApp",
        // "Click on position "+selectedPosition+" , pos="+position+" , id="+id);
      }
    });*/

    list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
        //int selectedPosition = adapterView.getSelectedItemPosition();
        // Log.i("SampleApp",
        // "Long click on position "+selectedPosition+" , pos="+position+" , id="+id);
        //currItemOnContextMenu = id;
        
        
        StringBuilder sb = new StringBuilder().append("insert into " + Helper.TBL_ROUTE + " (rdate, id_agent) VALUES ('").append(app.mYear).append("-").append(app.mMonth < 9 ? "0" : "").append(app.mMonth + 1)
            .append("-").append(app.mDay).append("', " + id + ")");
        DemandsActivity.db.execSQL(sb.toString());
        //currItemOnContextMenu = 0;
        if (app.routesActivity!=null)
          app.routesActivity.setAdapterRoutes();
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(30);
        Toast toast=Toast.makeText(AgentsActivity.this, "Точка добавлена в маршрут", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
        //Animation anim= AnimationUtils.loadAnimation(AgentsActivity.this, R.anim.test);
        //btn.setAnimation(anim);
        //view.setAnimation(anim);
        return false;
      }
    });

    /*list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
      public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
        // AdapterContextMenuInfo mi = (AdapterContextMenuInfo)
        // menuInfo;
        menu.setHeaderTitle("Действия");
        menu.add(0, 0, 0, "Добавить в маршрут");
      }
    });*/

  }

  @Override
  public void onResume() {
    super.onResume();
    list.requestFocus();
  }

/*  @Override
  public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals("Добавить в маршрут")) {
      // function1(item.getItemId());
      StringBuilder sb = new StringBuilder().append("insert into " + Helper.TBL_ROUTE + " (rdate, id_agent) VALUES ('").append(app.mYear).append("-").append(app.mMonth < 9 ? "0" : "").append(app.mMonth + 1)
          .append("-").append(app.mDay).append("', " + currItemOnContextMenu + ")");
      DemandsActivity.db.execSQL(sb.toString());
      currItemOnContextMenu = 0;
      app.routesActivity.setAdapterRoutes();
    } else {
      return false;
    }
    return true;
  }*/

  private FilterQueryProvider filterQueryProvider = new FilterQueryProvider() {
    @Override
    public Cursor runQuery(CharSequence _constraint) {
      Cursor c;
      StringBuilder sb = new StringBuilder();
      sb.append("select " + BaseColumns._ID + "," + Helper.TBL_AGENT_NAME + "," + Helper.TBL_AGENT_ADDRESS + " from " + Helper.TBL_AGENT);
      if (_constraint != null && _constraint.length() > 0) {
        sb.append(" where " + Helper.TBL_AGENT_NAME + " like '%" + _constraint.toString() + "%' ");
      }
      sb.append(" order by " + Helper.TBL_AGENT_NAME + " asc");
      c = DemandsActivity.db.rawQuery(sb.toString() , null);
      c.moveToFirst();
      startManagingCursor(c);
      return c;
    }
  };

  /*private FilterQueryProvider myQueryProvider = new FilterQueryProvider() {

    @Override
    public Cursor runQuery(CharSequence constraint) {
      return null;
    }
  };*/


  public void setAdapterAgents() {
    final String AgentsFields[] = { Helper.TBL_AGENT_NAME, Helper.TBL_AGENT_ADDRESS, BaseColumns._ID };
    final int[] AgentsTo = new int[] { android.R.id.text1, android.R.id.text2 };
    Cursor data = DemandsActivity.db.query(Helper.TBL_AGENT, AgentsFields, Helper.TBL_AGENT_IS_ARC + "=0", null, null, null, Helper.TBL_AGENT_NAME + " asc");
    startManagingCursor(data);
    CursorAdapter dataSource = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, data, AgentsFields, AgentsTo);
    list.setAdapter(dataSource);
    // list.setAdapter(new
    // ArrayAdapter(this,android.R.layout.simple_list_item_1,a.list1));
    list.setTextFilterEnabled(true);
  }

/*  private Cursor getAllAgents(SQLiteDatabase db) {
    Cursor c = db.rawQuery("select " + BaseColumns._ID + "," + Helper.TBL_AGENT_NAME + "," + Helper.TBL_AGENT_ADDRESS + " from " + Helper.TBL_AGENT + " order by " + Helper.TBL_AGENT_NAME + " asc", null);
    c.moveToFirst();
    return c;
  };

  private Cursor getFilteredAgents(SQLiteDatabase db, String s) {
    Cursor cur = db.rawQuery("select " + BaseColumns._ID + "," + Helper.TBL_AGENT_NAME + "," + Helper.TBL_AGENT_ADDRESS + " from " + Helper.TBL_AGENT + " where " + Helper.TBL_AGENT_NAME + " like '%" + s + "%' order by " + Helper.TBL_AGENT_NAME + " asc", null);
    cur.moveToFirst();
    return cur;
  };
*/
  
}